package com.fast.fast.common.feign.config;

import feign.RequestInterceptor;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Feign配置类
 *
 * @author lyf
 * @date 2022/01/01 00:00 周六
 **/
@RequiredArgsConstructor
@AutoConfiguration
public class FeignConfig {

    private final ObjectFactory<HttpMessageConverters> messageConverters;

    /**
     * Feign的请求拦截器
     * 同步请求头数据,防止在远程调用时丢失请求头
     *
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                HttpServletRequest request = requestAttributes.getRequest();
                // 同步请求头数据
                String tenantId = request.getHeader("tenantId");
                String satoken = request.getHeader("satoken");
                requestTemplate.header("tenantId", tenantId);
                requestTemplate.header("satoken", satoken);
            }
        };
    }

    /**
     * Feign的form编码器，让Feign支持form表单提交
     *
     * @return
     */
    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }
}

